import axios from 'axios'
import { useAuthStore } from '@/stores/auth.js'
import { useRouter } from 'vue-router'

const GLOBAL_HOST = import.meta.env.VITE_GLOBAL_HOST || 'localhost';
console.log('GLOBAL_HOST:', GLOBAL_HOST)
// 创建axios实例
const service = axios.create({
    baseURL: `http://${GLOBAL_HOST}:5000/api`,
    // baseURL: process.env.API_ROOT,
    // timeout: 80000, // 请求超时时间
     withCredentials: true,
    // crossDomain: true
})

// request拦截器
service.interceptors.request.use(
    config => {
        const authStore = useAuthStore()
       if (authStore.accessToken) {
      config.headers['Authorization'] = `Bearer ${authStore.accessToken}`
    }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)


// response 拦截器
service.interceptors.response.use(
    (response) => response.data,
   
    async (error) => {
      const originalRequest = error.config
      const router = useRouter()
      if(error.response.status = 401 && !originalRequest._retry){
        originalRequest._retry = true
        const authStore =  useAuthStore()
        try{

        const axiosInstance = axios.create({
            withCredentials: true,

          });
          // 使用refreshToken去请求
          const response = await axiosInstance.post(
            `http://${GLOBAL_HOST}:5000/api/auth/refresh`,{},
            {
              headers:{
                'Authorization': `Bearer ${authStore.refreshToken}`
              }
            }
            )
        if (response && response.access_token) {
          // 更新 store 中的 token
          authStore.setAccessToken(response.access_token)
           // 更新原始请求的Authorization头
            originalRequest.headers['Authorization'] = `Bearer ${response.access_token}`
            return service(originalRequest)

        }
        // 如果没有刷新 token 的接口，直接清除认证状态
        authStore.clearAuth()
        // 重定向到登录页面
        await router.push('/login')
      }catch (refreshError){
          authStore.clearAuth()
        // 重定向到登录页面
        await router.push('/login')
           return Promise.reject(error)
        }
      }
      console.log('err' + error) // for debug
      return Promise.reject(error)
    }
  )
export default service
